# Detect the GCC version
GCC_VER       := $(shell gcc -v 2>&1 | grep 'gcc version' | awk '{print $$3}')
GCC_MAJOR_VER := $(shell echo $(GCC_VER) | awk -F '.' '{print $$1$$2;}')

ifdef BOOST_SOURCE
# For "source" boost installations under Linux or Darwin.
# You need to have built the boost unit test framework.
BOOST_VERSION := 1_38
BOOST_ROOT    := /opt/boost/boost_$(BOOST_VERSION)_0
BOOST_INCLUDE := -I$(BOOST_ROOT)
BOOST_LIBS    := -L$(BOOST_ROOT)/bin.v2/libs/test/build/gcc-$(GCC_VER)/release/threading-multi/
BOOST_TEST    := -lboost_unit_test_framework-gcc$(GCC_MAJOR_VER)-mt-$(BOOST_VERSION)
else
# For "normal" boost installations under Linux and MacPorts installations under
# Darwin.
BOOST_INCLUDE := -I/opt/local/include
BOOST_LIBS    := -L/opt/local/lib
BOOST_TEST    := -lboost_unit_test_framework-mt
endif

WOPTIONS_SRCS = $(wildcard woptions/*.cpp)
WOPTIONS_HDRS = $(wildcard woptions/*.h) $(wildcard woptions/detail/*.h)
WOPTIONS_OBJS = $(addprefix bin/,$(patsubst %.cpp,%.o,$(WOPTIONS_SRCS)))
LIBWOPTIONS   = bin/libwoptions.a

TESTS_SRCS = $(wildcard tests/*.cpp)
TESTS_HDRS = $(wildcard tests/*.h)
TESTS_OBJS = $(addprefix bin/,$(patsubst %.cpp,%.o,$(TESTS_SRCS)))
TESTS_BIN  = bin/woptions-tests

EXAMPLE_SRCS = $(wildcard examples/*.cpp)
EXAMPLE_BINS = $(patsubst examples/%.cpp,bin/%,$(EXAMPLE_SRCS))

CC            = g++
CFLAGS        = -g $(BOOST_INCLUDE) -Wall -Wconversion -Wshadow -I. -DBOOST_TEST_DYN_LINK

ifndef DEBUG
CFLAGS += -O3 
endif

.PHONY: all clean docs

all: $(LIBWOPTIONS) $(TESTS_BIN) $(EXAMPLE_BINS) docs

docs: docs/html/index.html

clean:
	rm -f $(LIBWOPTIONS) $(TESTS_BIN) $(WOPTIONS_OBJS) $(TESTS_OBJS)
	rm -rf docs

$(LIBWOPTIONS): $(WOPTIONS_OBJS)
	@mkdir -p $(@D)
	@ rm -f $@
	$(AR) rcs $@ $^
	
$(TESTS_BIN): $(TESTS_OBJS) $(LIBWOPTIONS)
	@mkdir -p $(@D)
	@rm -f $@
	$(CC) -o $@ $^ $(CFLAGS) $(BOOST_LIBS) $(BOOST_TEST)

docs/html/index.html: Doxyfile $(WOPTIONS_SRCS) $(WOPTIONS_HDRS)
	doxygen $<

bin/%: examples/%.cpp $(LIBWOPTIONS)
	@mkdir -p $(@D)
	@rm -f $@
	$(CC) -o $@ $^ $(CFLAGS)

bin/%.o: %.cpp $(WOPTIONS_HDRS) $(TESTS_HDRS)
	@mkdir -p $(@D)
	$(CC) -c -o $@ $< $(CFLAGS)
